Working with JSON

JSON stands for JavaScript Object Notation. JSON is a lightweight format for storing and transporting data. It is "self-describing" and easy to understand

JSON is often used when data is sent from a server to a web page


JSON Syntax Rules

"employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ]

Basic tools when working with JSON

The first thing is to find a JSON validator website, and a good example is jsonlint.com. You can copy and paste your JSON files and click on Validate JSON , and your current JSON data will be analyzed. If any errors are found, the tool will provide some guidance to fix it.

ConvertTo-Json

The ConvertTo-Json cmdlet converts any .NET object to a string in JavaScript Object Notation (JSON) format. The properties are converted to field names, the field values are converted to property values, and the methods are removed.

Get-Date | Select-Object -Property * | ConvertTo-Json (Get-UICulture).Calendar | ConvertTo-Json

ConvertFrom-Json

The ConvertFrom-Json cmdlet converts a JavaScript Object Notation (JSON) formatted string to a custom PSCustomObject object that has a property for each field in the JSON string.

Get-Date | Select-Object -Property * | ConvertTo-Json | ConvertFrom-Json

Get JSON strings from a web service and convert them to PowerShell objects

This command uses the Invoke-WebRequest cmdlet to get JSON strings from a web service and then it uses the ConvertFrom-Json cmdlet to convert JSON content to objects that can be managed in PowerShell.

$response = Invoke-WebRequest -Uri 'https://jsonplaceholder.typicode.com/users' -UseBasicParsing $response $users = $response | ConvertFrom-Json $users | FT

Invoke-WebRequest

The Invoke-WebRequest cmdlet sends HTTP and HTTPS requests to a web page or web service. It parses the response and returns collections of links, images, and other significant HTML elements.

$response = Invoke-WebRequest -Uri 'https://jsonplaceholder.typicode.com/users' -UseBasicParsing $response